/*
 * @Description: 工具库
 * @Version: 1.0
 * @Autor: JiaJun Wu
 * @Date: 2021-09-07 09:58:04
 * @LastEditors: JiaJun Wu
 * @LastEditTime: 2021-09-23 16:54:10
 */
use super::*;
pub mod date_time;
pub mod request;
pub mod responses;
use bson::ordered::OrderedDocument;
use md5;
pub mod serialize;
use r2d2_mongodb::mongodb::cursor::Cursor;

#[rocket::async_trait]
pub trait CursorAsVec {
    async fn as_vec(&mut self) -> Result<Vec<OrderedDocument>, std::io::Error>;
}

#[rocket::async_trait]
impl CursorAsVec for Cursor {
    async fn as_vec(&mut self) -> Result<Vec<OrderedDocument>, std::io::Error> {
        let mut list = vec![];
        while let Some(result) = self.next() {
            list.push(result.unwrap());
        }
        Ok(list)
    }
}

/// 安全密鑰
const SECRET_KEYS: &str = "!s@w4$qS%^(_123-=0Xha9452sLW^%sfa9)\\";

/// md5
#[inline]
pub fn md5_str(content: &str) -> String {
    let encrypt = md5::compute(content);
    format!("{:x}", encrypt)
}

/// 自定义 安全密钥 生成密码
#[inline]
pub fn get_password(real_password: &str, secret_key: &str, secret: &str) -> String {
    let origin = format!("{}-{}-{}", real_password, secret_key, secret);
    md5_str(origin.as_str())
}

/// 使用默认 安全密钥 生成密码
#[inline]
pub fn get_password_default(real_password: &str) -> String {
    get_password(
        real_password,
        SECRET_KEYS,
        &*super::config::toml_conf::SETTING.secret_key,
    )
}

/// ip转i64
#[inline]
pub fn ip2_i64(ip: &str) -> i64 {
    let ip: Vec<i64> = ip.split('.').map(|x| x.parse().unwrap_or(0)).collect();
    if ip.len() >= 3 {
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + (ip[3]);
    }
    return 0;
}

/// i64转ip
#[inline]
pub fn i642_ip(ip_i64: &i64) -> String {
    let mut ip = String::new();
    ip += &(ip_i64 >> 24).to_string();
    ip += ".";
    ip += &((ip_i64 >> 16) & 0xFF).to_string();
    ip += ".";
    ip += &((ip_i64 >> 8) & 0xFF).to_string();
    ip += ".";
    ip += &(ip_i64 & 0xFF).to_string();
    ip
}
